//
//  MultiThreading.m
//  Finance
//
//  Created by cheng xiang on 13-4-6.
//  Copyright (c) 2013年 cheng xiang. All rights reserved.
//

#import "MultiThreading.h"

@implementation MultiThreading

+ (void)getDataFromNetwork: (NSString *)url toObject:(NSObject *)obj callBack:(SEL)method withBody:(NSData *)body
{    
    //使用gcd实现异步请求数据 add by chengxiang 20130406
    dispatch_queue_t downloadQueue = dispatch_queue_create("downing data", NULL);
    dispatch_async(downloadQueue, ^{
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
        [request setHTTPMethod:@"POST"];
        [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request addValue:@"length" forHTTPHeaderField:@"Content-Length"];
        [request setHTTPBody:body];
        NSHTTPURLResponse *urlResponse = nil;
        NSError *error = nil;
        NSData *recervedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
        NSLog(@"error inof %@",error);
        if(recervedData == nil)
        {
            return ;
        }
        NSError *derror = nil;
            NSString *results = [[NSString alloc] initWithBytes:[recervedData bytes] length:[recervedData length] encoding:NSUTF8StringEncoding];
        NSLog(@"%@",results);
        //    NSData *jsonData = [results dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:recervedData options:NSJSONReadingMutableContainers error:&derror];
        NSLog(@"%@",dic);
        
        
        NSObject *header = [dic objectForKey:@"header"];
        if ([header isKindOfClass:[NSDictionary class]] && [(NSDictionary *)header objectForKey:@"returnCode"] != nil) {
            NSString *returnCode = [(NSDictionary *)header objectForKey:@"returnCode"];
            NSLog(@"return code = %@",returnCode);
//            [returnCode isEqualToString:@"00"] || [returnCode isEqualToString:@"0000"] || [returnCode isEqualToString:@"UL00"]
            if (true) {
                //判断返回码成功才回调
                dispatch_async(dispatch_get_main_queue(), ^{
                    if ([obj respondsToSelector:method]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
                        [obj performSelector:method withObject:dic];
#pragma clang diagnostic pop
                    }
                });
                
            }
        }
        
    });
        
}

@end
